// ==UserScript==
// @name         愉快的二手东
// @namespace    aduil.com
// @version      0.1
// @description  fetching used product after once click
// @author       You
// @match        https://paipai.jd.com/auction-detail/*
// @grant        none
// ==/UserScript==

class DBD {
    constructor() {
        this.price = 0;
        this.auctionId = null;
        window.getTakId = ()=>{return '';};
        let regex = new RegExp(/auction-detail\/(\d+)/);
        this.auctionId = regex.exec(location.pathname)[1];
        window.getJdEid(eid=>{
            this.eid = eid
            this.takid = window.getTakId()
        });
        this.cfgs = {
            topPrice: 100,
            addPrice: -1,
            offerAgo: 150,
            flushAgo: 2000,
            flushFrequency: 200
        };
        this.initPanel();
    }
    // 查询信息
    getDetail() {
        this.jsonp({url: "//used-api.jd.com/auction/detail", data:{auctionId: this.auctionId},callback:'callback',success:(data)=>{
            this.detailInfo = data.data;
            console.log(data.data)
            this.setAuto()
        }})
    }
    // 查询价格
    getPrice() {
        this.jsonp({url: "//used-api.jd.com/auctionRecord/getCurrentAndOfferNum", data:{auctionId: this.auctionId},callback:'callback',success:(data)=>{
            this.price = data.data.currentPrice;
        }})
    }
    // 自动成交价
    setAutoPrice() {
        clearInterval(this.itv);
        this.itv = setInterval(() => {
            this.getPrice()
        }, this.cfgs.flushFrequency);
    }
    // 设置定时自动出价
    setAuto() {
        this.endTime = this.detailInfo.auctionInfo.endTime;
        this.currentTime = this.detailInfo.currentTime;
        this.price = this.detailInfo.auctionInfo.currentPrice;
        if (this.currentTime < this.endTime) {
            clearTimeout(this.tm1);
            clearTimeout(this.tm2);
            this.tm1 = setTimeout(()=>{
                this.offerPrice()
            }, this.endTime - this.currentTime - this.cfgs.offerAgo)
            this.tm2 = setTimeout(()=>{ // 提前3秒开始刷价格
                this.setAutoPrice()
            }, this.endTime - this.currentTime - this.cfgs.flushAgo)
        } else {
            alert("兄dei这盘黄花儿菜早就凉了");
        }
    }
    // 出价
    offerPrice() {
        console.log(window.getTakId());
        let url = "https://used-api.jd.com/auctionRecord/offerPrice";
        let bidPrice = parseInt(this.price) + parseInt(this.cfgs.addPrice);
        let bodyData = this.formatParams({
            auctionId: this.auctionId,
            price: bidPrice,
            trackId: window.getTakId(),
            eid: this.eid
        });
        if (bidPrice > this.cfgs.topPrice) {
            alert("报价" + bidPrice + "，超出预算了，不下单");
            clearInterval(this.itv);
        } else {
            fetch(url,{
                method: "POST",
                credentials: 'include',
                headers: {"Content-Type": "application/x-www-form-urlencoded"
                         },
                body: bodyData
            }).then(resp=> {
                resp.json().then(data => {
                    console.log(data)
                    clearInterval(this.itv);
                    alert(data.message);
                })
            })
        }
    }
    // jsonp
    jsonp(options) {
        options = options || {};
        if (!options.url || !options.callback) {
            throw new Error("参数不合法");
        }

        //创建 script 标签并加入到页面中
        var callbackName = ('jsonp_' + Math.random()).replace(".", "");
        var oHead = document.getElementsByTagName('head')[0];
        options.data[options.callback] = callbackName;
        var params = this.formatParams(options.data);
        var oS = document.createElement('script');
        oHead.appendChild(oS);

        //创建jsonp回调函数
        window[callbackName] = function (json) {
            oHead.removeChild(oS);
            clearTimeout(oS.timer);
            window[callbackName] = null;
            options.success && options.success(json);
        };
        //发送请求
        oS.src = options.url + '?' + params;

        //超时处理
        if (options.time) {
            oS.timer = setTimeout(function () {
                window[callbackName] = null;
                oHead.removeChild(oS);
                options.fail && options.fail({ message: "超时" });
            }, time);
        }
    };

    //格式化参数
    formatParams(data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
        }
        return arr.join('&');
    }
    // 存储配置
    setCfg(cfgs) {
        this.cfgs = cfgs;
    }
    // 控制面板
    initPanel() {
        let html = `
<div style="z-index: 101; background: #f1f1f1; padding: 10px; width: 200; height: 180; right: 0; position: fixed; top: calc((100% - 180px) / 2)">
<div>
<label>最高价位</label>
<input id="cfg-topPrice" type="text" value="${this.cfgs.topPrice}">
</div>
<div>
<label>单次加价</label>
<input id="cfg-addPrice" type="text" value="${this.cfgs.addPrice}">
</div>
<div>
<label>提前下單(ms)</label>
<input id="cfg-offerAgo" type="text" value="${this.cfgs.offerAgo}">
</div>
<div>
<label>提前刷价(ms)</label>
<input id="cfg-flushAgo" type="text" value="${this.cfgs.flushAgo}">
</div>
<div>
<label>刷价频率(ms)</label>
<input id="cfg-flushFrequency" type="text" value="${this.cfgs.flushFrequency}">
</div>
<div><button onclick="dbd.setCfg({
topPrice: document.getElementById('cfg-topPrice').value,
addPrice: document.getElementById('cfg-addPrice').value,
offerAgo: document.getElementById('cfg-offerAgo').value,
flushAgo: document.getElementById('cfg-flushAgo').value,
flushFrequency: document.getElementById('cfg-flushFrequency').value
});dbd.getDetail();
this.innerHTML = '更新配置';
">一键启动</button></div>
`;
        let div = document.createElement('div');
        div.innerHTML = html;
        document.body.appendChild(div);
    }
}

window.dbd = new DBD();
